<template>
  <div class="login">
    <div v-loading="loading">
<!--    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">-->
      <h3 class="title">智简自媒体管理系统</h3>
      <div style="height: 280px;text-align: center">
          <img v-if="!loading" :src="QRCodeImg" style="width: 240px;height: 240px"  alt=""/>
      </div>

<!--      <el-form-item style="width:100%;">-->
        <div style="float: right;"  >
          <router-link class="link-type"  :to="'/login'">账号密码登录</router-link>
        </div>
<!--      </el-form-item>-->
<!--    </el-form>-->
    </div>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2023 <a href="https://beian.miit.gov.cn" target="_blank">陕ICP备2021000905号-3</a></span>
    </div>
  </div>
</template>

<script>
import { getCodeImg,getQRCode } from "@/api/login";
import Cookies from "js-cookie";
import { getToken, setToken, removeToken } from '@/utils/auth'
import { encrypt, decrypt } from '@/utils/jsencrypt'
import {getScanCode} from "../api/login";
export default {
  name: "Login",
  data() {
    return {
      codeUrl: "",
      QRCodeImg:'',
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      count: 5 * 60, //二维码失效时间为五分钟
      loading: false,
      ticket:'', //二维码验证参数
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    },
    'QRCodeImg'(val){
      this.count = 0;
    }
  },
  created() {
    this.getQRCode();
    this.getCookie();
  },

  methods: {

    //获取小程序登录二维码
   async getQRCode() {
      this.loading = true;
     await getQRCode().then(res =>{
        this.ticket = res.data.ticket;
        console.log(res.data.ticket)
        this.QRCodeImg = "data:image/png;base64," + res.data.scanQRCode ;
        console.log(this.QRCodeImg)
        this.loading = false;
      })
      console.log(this.ticket)
     await this.getLoginData(this.ticket);
    },


    /**
     * 获取扫码登录返回数据
     */
   async getLoginData(ticket){
     if(this.$route.path !== '/scanLogin'){
       return;
     }
     this.count --;
       getScanCode(ticket).then(async (res)=>{
       console.log(res)
         if(res.data.status !== 0){  //已扫码
           this.count = 0;
           if(res.data.status === -1){  //未注册
             let openId = res.data.openId; //获取用户openid
             await this.$router.push({path: '/register',query:{ id:openId }})
           }else if(res.data.status === 1){ //跳转登录
             setToken(res.data.token)
             console.log(res.data.token)
             await this.$router.push({ path: this.redirect || "/" }).catch(()=>{});
           }
         }else{
           setTimeout(()=>{
             this.getLoginData(ticket)
           },1000)
         }
      });
    },





    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove('rememberMe');
          }
          this.$store.dispatch("Login", this.loginForm).then(() => {
            this.$router.push({ path: this.redirect || "/" }).catch(()=>{});
          }).catch(() => {
            this.loading = false;
            if (this.captchaEnabled) {
              this.getCode();
            }
          });
        }
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-color: #1f2d3d;
  //background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 38px;
}
</style>
